package cn.fxyz.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.fxyz.cart.Cart;
import cn.fxyz.cart.CartItem;
import cn.fxyz.entity.Food;
import cn.fxyz.service.FoodService;

/**
 * 购物车Action
 * 
 * @author 传智.郭嘉
 * 
 */
@Controller
@RequestMapping("/cart")
public class CartController {
	// 注入商品的Service
	@Resource
	private FoodService foodService;

	public void setFoodService(FoodService foodService) {
		this.foodService = foodService;
	}

	// 将购物项添加到购物车:执行的方法
/*	@RequestMapping("addCart")
	public String addCart(Model model,Food food,Integer count,HttpServletRequest request) {
		// 封装一个CartItem对象.
		CartItem cartItem = new CartItem();
		// 设置数量:
		cartItem.setFoodCount(count);
		// 根据pid进行查询商品:
		Food food1 = foodService.findById(food);
		// 设置商品:
		cartItem.setFood(food1);
		// 将购物项添加到购物车.
		// 购物车应该存在session中.
		Cart cart = (Cart) request.getSession()
				.getAttribute("cart");
		if (cart == null) {
			System.out.println(222);
			cart = new Cart();
			request.getSession().setAttribute("cart", cart);
		}
		cart.addCart(cartItem);
		return "reception/detail/clientCart";
	}*/
	@RequestMapping("addCart")
	public @ResponseBody Cart addCart(Model model,Food food,Integer count,HttpServletRequest request) {
		// 封装一个CartItem对象.
		CartItem cartItem = new CartItem();
		// 设置数量:
		cartItem.setFoodCount(count);
		// 根据pid进行查询商品:
		Food food1 = foodService.findById(food);
		// 设置商品:
		cartItem.setFood(food1);
		// 将购物项添加到购物车.
		// 购物车应该存在session中.
		Cart cart = (Cart) request.getSession()
				.getAttribute("cart");
		if (cart == null) {
			cart = new Cart();
			request.getSession().setAttribute("cart", cart);
		}
		cart.addCart(cartItem);
		return cart;
	}

	// 清空购物车的执行的方法:
	@RequestMapping("clearCart")
	public String clearCart(HttpServletRequest request){
		// 获得购物车对象.
		Cart cart = (Cart) request.getSession()
				.getAttribute("cart");
		if (cart == null) {
			cart = new Cart();
			request.getSession().setAttribute("cart", cart);
		}
		// 调用购物车中清空方法.
		cart.clearCart();
		return "clearCart";
	}
	
	// 从购物车中移除购物项的方法:
	@RequestMapping("removeCart")
	public @ResponseBody String removeCart(Integer id,HttpServletRequest request){
		// 获得购物车对象
		Cart cart = (Cart) request.getSession()
				.getAttribute("cart");
		if (cart == null) {
			cart = new Cart();
			request.getSession().setAttribute("cart", cart);
		}
		// 调用购物车中移除的方法:
		cart.removeCart(id);
		// 返回页面:
		return "success";
	}
	
	// 我的购物车:执行的方法
	@RequestMapping("myCart")
	public String myCart(){
		return "myCart";
	}
	
}
